package cn.sylinx.horm.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public abstract class BeanUtil {

    private static final Map<Class<?>, PropertyDescriptor[]> beanPropMap = new HashMap<>();
    private static final Object beanPropLock = new Object();

    private BeanUtil() {
    }

    // 把JavaBean转化为map
    public static Map<String, Object> bean2map(Object bean) {
        try {
            return bean2mapInner(bean);
        } catch (Exception e) {
            GLog.error("bean2map error" + e.getMessage(), e);
            return new HashMap<String, Object>();
        }
    }

    // 把JavaBean转化为map
    private static Map<String, Object> bean2mapInner(Object bean) throws Exception {
        Map<String, Object> map = new HashMap<>();
        // 获取JavaBean的描述器
        // 获取属性描述器
        PropertyDescriptor[] pds = getBeanProperties(bean.getClass());
        // 对属性迭代
        for (PropertyDescriptor pd : pds) {
            // 属性名称
            String propertyName = pd.getName();
            // 属性值,用getter方法获取
            Method m = pd.getReadMethod();
            Object properValue = m.invoke(bean);// 用对象执行getter方法获得属性值
            // 把属性名-属性值 存到Map中
            map.put(propertyName, properValue);
        }
        return map;
    }

    private static PropertyDescriptor[] getBeanProperties(Class<?> beanClass) throws Exception {

        PropertyDescriptor[] pds = beanPropMap.get(beanClass);
        if (pds == null) {
            synchronized (beanPropLock) {
                pds = beanPropMap.get(beanClass);
                if (pds == null) {
                    // 获取JavaBean的描述器
                    BeanInfo b = Introspector.getBeanInfo(beanClass, Object.class);
                    pds = b.getPropertyDescriptors();
                    beanPropMap.put(beanClass, pds);
                }
            }
        }
        return pds;
    }
}
